package com.controller.sys;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: EmailFileUpload
 * @Author: ARongzhe
 * @Date: 2022/04/29 10:33:19
 * @Description: TODO
 */
@RestController
@RequestMapping(value = "/emailFile")
public class EmailFileUpload {

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws FileNotFoundException {
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) path = new File("");
        if (file != null) {
            String fileName = System.currentTimeMillis() + (int) (Math.random() * 1000) + "_" + file.getOriginalFilename();//生产随机名称
            System.out.println("打开文件... ");
            File img = new File(path.getAbsolutePath() + "\\static\\email\\file\\" + fileName);
            System.out.println(img.toString());
            File dir = new File(path.getAbsolutePath() + "\\static\\email\\file");
            System.out.println(dir);
            try {
                if (!dir.exists()) {
                    dir.mkdir();
                }
                if (!img.exists()) {
                    img.createNewFile();
                }
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(img));
                bos.write(file.getBytes());
                bos.flush();
                bos.close();
                Map<String, Object> m = new HashMap<String, Object>();
                m.put("src", "email\\file\\" + fileName);
                return new ResponseEntity(m.values(), HttpStatus.OK);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return new ResponseEntity<String>("", HttpStatus.OK);
        }

        return new ResponseEntity<String>("", HttpStatus.OK);
    }
}
